package com.juyu.miliao.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author jh
 * 15:54
 */
@Configuration
public class RestTemplateConfig {

	/**
	 * 注入restTemplate 配置
	 */
	@Bean
	RestTemplate restTemplate() {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		//超时
		requestFactory.setConnectTimeout(1000);
		requestFactory.setReadTimeout(1000);
		RestTemplate restTemplate = new RestTemplate(requestFactory);

		//注:不同解析器中字符集是不一样的,debug可以看到messageConverters是一个list,根据自己需要添加设置
		//如果要发送的话,设置请求头
		List<HttpMessageConverter<?>> c = restTemplate.getMessageConverters();
		for (HttpMessageConverter<?> mc : c) {
			if (mc instanceof StringHttpMessageConverter) {
				StringHttpMessageConverter mcc = (StringHttpMessageConverter) mc;
				mcc.setDefaultCharset(Charset.forName("UTF-8"));
			}
		}

		return restTemplate;

//		StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
//		return new RestTemplateBuilder()
//				.setConnectTimeout(1000)
//				.setReadTimeout(1000)
//				//默认ISO-8859-1 配置utf-8解决中文乱码
////				.additionalMessageConverters(converter)
//				.build();
	}


}
